import wave
from math import log
import numpy as np
import pyaudio


def outputDB():
    wf = wave.open('output1.wav'  , "rb")

    # 返回音频总帧数
    nframes = wf.getnframes()

    # 读取并返回以 bytes 对象表示的最多 n 帧音频，一般 n 为 nframes（总帧数）
    wavedata = wf.readframes(nframes)

    # 返回采样字节长度
    wavewidth = wf.getsampwidth()

    # 返回声道数量（1 为单声道，2 为立体声）
    wavechannel = wf.getnchannels()

    # 返回采样频率
    framerate = wf.getframerate()

    print(nframes,wavewidth,wavechannel,framerate )



    wavedata = np.frombuffer(wavedata, dtype=np.short)
    print(wavedata)
    wavedata = wavedata.T
    print(wavedata)
    wavedata = abs(wavedata)

    print(wavedata)
    sum_data = sum(wavedata)
    avg_data = sum_data / len(wavedata)
    print('sum_data = ',sum_data,'  avg_data = ',avg_data,max(wavedata))

    fenbei1 = 20 * log(max(wavedata), 10)  # 最大分贝值
    #fenbei2 = 20 * log(median(wavedata), 10)  # 中位数
    fenbei3 = 20 * log(avg_data, 10)  # 平均值
    print(fenbei1)


outputDB()